package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;

import com.sky.service.OrdersStatisticsService;

import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrdersStatisticsServiceImpl implements OrdersStatisticsService {
    //    @Autowired
//    private ReportMapper reportMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list = new ArrayList<>();
        List<Double> price = new ArrayList<>();
        list.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        String join = StringUtils.join(list, ",");
        for (LocalDate time : list) {
            LocalDateTime timeBegin = LocalDateTime.of(time, LocalTime.MIN);
            LocalDateTime timeEnd = LocalDateTime.of(time, LocalTime.MAX);
            Integer completed = Orders.COMPLETED;
            Double totalPrice = orderMapper.sumAmount(timeBegin, timeEnd, completed);
            totalPrice=totalPrice==null? 0.0:totalPrice;
            price.add(totalPrice);
        }
        String priced = StringUtils.join(price, ",");
        return TurnoverReportVO.builder().dateList(join).turnoverList(priced).build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list = new ArrayList<>();
        List<Integer> NewUser = new ArrayList<>();
        List<Integer> totalUser = new ArrayList<>();
        list.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        String join = StringUtils.join(list, ",");
        for (LocalDate date : list) {
            LocalDateTime timeBegin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime timeEnd = LocalDateTime.of(date, LocalTime.MAX);
            Integer newu = orderMapper.countUser(timeBegin, timeEnd);
            Integer user = orderMapper.countUser(null, timeEnd);
            NewUser.add(newu);
            totalUser.add(user);
        }
        return UserReportVO.builder().dateList(join).newUserList(StringUtils.join(NewUser,",")).totalUserList(StringUtils
                .join(totalUser,",")).build();
    }

    @Override
    public OrderReportVO OrderStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list = new ArrayList<>();
        List<Integer> ordercount = new ArrayList<>();
        List<Integer> completeOrderCount = new ArrayList<>();
        list.add(begin);

        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            list.add(begin);
        }
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;
        Double orderCompletionRate=0.0;
        String join = StringUtils.join(list, ",");
        for (LocalDate date : list) {
            LocalDateTime timeBegin = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime timeEnd = LocalDateTime.of(date, LocalTime.MAX);
            Integer totalOrder = orderMapper.selectOrder(timeBegin, timeEnd);

            totalOrderCount += totalOrder;
            ordercount.add(totalOrder);
            Integer completeOrder = orderMapper.selectcompleteOrder(timeBegin, timeEnd, Orders.COMPLETED);

            validOrderCount += completeOrder;
            completeOrderCount.add(completeOrder);

        }
        if (totalOrderCount!=0){
          orderCompletionRate=validOrderCount.doubleValue()/totalOrderCount;
        }

        return OrderReportVO.builder().dateList(join).orderCountList(StringUtils.join(ordercount,",")).
                validOrderCountList(StringUtils.join(completeOrderCount,",")).totalOrderCount(totalOrderCount).validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10Statistics(LocalDate begin, LocalDate end) {
        LocalDateTime Begin = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime End = LocalDateTime.of(end, LocalTime.MAX);
     List<GoodsSalesDTO> list= orderMapper.getsalestop10(Begin,end);
        List<String> namelist = list.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberlist = list.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());


        return SalesTop10ReportVO.builder().nameList(StringUtils.join(namelist,",")).numberList(StringUtils.join(numberlist,","))
                .build();
    }

    /**
     * 到处运营数据表
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) {
        //1.查询数据库获取运营数据--查询最近30天数据
        LocalDate Begin=LocalDate.now().minusDays(30);
        LocalDate End=LocalDate.now().minusDays(1);
       LocalDateTime timeBegin=LocalDateTime.of(Begin,LocalTime.MIN);
       LocalDateTime timeEnd=LocalDateTime.of(End,LocalTime.MAX);
        BusinessDataVO businessDataVO = workspaceService.getBusinessData(timeBegin, timeEnd);

        //通过poi将数据写入excel表中
       // InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
       // InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel = new XSSFWorkbook(inputStream);
            XSSFSheet sheet1 = excel.getSheet("Sheet1");
            sheet1.getRow(1).getCell(1).setCellValue(Begin+"至"+End);
            sheet1.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet1.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet1.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet1.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet1.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            for (int i = 0; i < 30; i++) {
                LocalDate date=Begin.plusDays(i);
                LocalDateTime BeginDate=LocalDateTime.of(date,LocalTime.MIN);
                LocalDateTime EndDate=LocalDateTime.of(date,LocalTime.MAX);
                BusinessDataVO businessData = workspaceService.getBusinessData(BeginDate, EndDate);
                XSSFRow row = sheet1.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());


            }

            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);
            //关闭资源
            outputStream.flush();
            outputStream.close();
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //通过输出流就excel文件下载到浏览器中
    }
}